# !/usr/bin/env python
# -*- coding:utf-8 -*-
# project name: bitu-Interface-test
# author: "Lei Yong" 
# creation time: 2019/7/31 15:10
# Email: leiyong711@163.com

import re
import curlify
import traceback
import datetime
from common.Request import Request
from common.ExcerRead import get_excel_data
from config import setting
from common.WriteReport import WriteReport

wr = WriteReport()
r = Request()


def parameterization(data):
    """
    :param data: 请求参数化入参替换r
    :return: 替换后的参数
    """
    try:
        body_data = re.findall(r"\${(.*?)}", data)
        for body_temp in body_data:
            data = data.replace("${%s}" % body_temp, setting.CONTEXT[body_temp])
    except Exception:
        pass
    return data


class CaseManage:

    # 响应断言
    def __init__(self):
        self.start_time = datetime.datetime.now()  # 记录程序开始运行时间
        self.url = ""

    def assertion_resp(self, response, case, curl):
        try:
            # 响应状态码断言
            if int(case["status_code"]) == response.status_code:
                for expect in case["expect_result"].split(','):
                    # 响应文本断言
                    if expect in response.text:
                        # 上文做下文入参 用作全局参数化
                        if case["parameter"] != "" or case["parameter"] != None:
                            for temp in case["parameter"].split(','):
                                if temp != "":
                                    # 提取Excel参数化并添加到全局字典变量
                                    setting.CONTEXT[re.findall(r'\$"(.*?)"', temp)[0]] = \
                                        re.findall(temp.replace("$", ""), response.text)[0]
                        end_time = (datetime.datetime.now() - self.start_time).total_seconds()
                        wr.write_log("PASS", case["fileName"], self.url, self.method, case["case_info"], end_time, curl=curl)
                    else:
                        raise AssertionError("响应文本断言失败")
            else:
                raise AssertionError("响应状态码断言失败")

        except:
            print(traceback.format_exc())
            err_log = traceback.format_exc()
            wr.inset_log(err_log)
            end_time = (datetime.datetime.now() - self.start_time).total_seconds()
            wr.write_log("FAIL", case["fileName"], self.url, self.method, case["case_info"], end_time, curl=curl)

    # 拼装请求数据
    def assembly(self, list_data):

        for i in list_data:
            self.start_time = datetime.datetime.now()  # 记录程序开始运行时间
            self.method = i["method"].upper()
            self.url = i["url"]
            body = i["body"]
            header = i["headers"]

            self.url = parameterization(self.url)  # url上下文参数化
            body = parameterization(body)  # body上下文参数化
            header = parameterization(header)  # headers上下文参数化
            curl = [""]
            try:
                if self.method == "GET":
                    response = r.Get(url=self.url, header=header)
                    curl = [curlify.to_curl(response.request).replace(r'"',r'\"')]
                    wr.inset_log("响应内容：{}".format(response.text))  # 写出响应到日志
                    print(f"curl: {curl}")
                    self.assertion_resp(response, i, curl)

                elif self.method == "POST":
                    wr.inset_log("请求参数: {}".format(body))
                    response = r.Post(url=self.url, data=body, header=header)
                    curl = [curlify.to_curl(response.request).replace(r'"',r'\"')]
                    print(f"curl: {curl}")
                    wr.inset_log("响应内容：{}".format(response.text))  # 写出响应到日志
                    self.assertion_resp(response, i, curl)

                else:
                    wr.inset_log("请求方式不正确")
                    end_time = (datetime.datetime.now() - self.start_time).total_seconds()
                    wr.write_log("FAIL", i["fileName"], self.url, self.method, i["case_info"], end_time, curl)
            except Exception as e:
                print(traceback.format_exc())
                print(e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, repr(e))
                err_log = traceback.format_exc()
                wr.inset_log(err_log)
                end_time = (datetime.datetime.now() - self.start_time).total_seconds()
                wr.write_log("FAIL", i["fileName"], self.url, self.method, i["case_info"], end_time, curl=curl)


if __name__ == "__main__":
    data = get_excel_data("case/Phone.csv")
    cm = CaseManage()
    cm.assembly(data)
    wr.end_Write('result/index.html')
